package com.xkcyy.one.ai.common.tool;

import com.fasterxml.jackson.databind.JsonNode;
import com.xkcyy.one.ai.llm.model.ToolDefinition;
import lombok.extern.slf4j.Slf4j;
import org.springframework.scripting.ScriptEvaluator;
import org.springframework.scripting.support.StaticScriptSource;

import java.util.Map;

/**
 * 脚本工具实现
 * 
 * @author yuand
 */
@Slf4j
public class ScriptTool extends AbstractTool {
    private final ScriptEvaluator scriptEvaluator;

    public ScriptTool(ToolDefinition definition, ScriptEvaluator scriptEvaluator) {
        super(definition);
        this.scriptEvaluator = scriptEvaluator;
    }

    @Override
    protected String executeInternal(String inputParams) {
        try {
            JsonNode params = objectMapper.readTree(inputParams);
            String script = params.get("script").asText();
            JsonNode scriptParams = params.get("params");

            Object result = scriptEvaluator.evaluate(
                    new StaticScriptSource(script),
                    scriptParams != null ? objectMapper.convertValue(scriptParams, Map.class) : null);

            return objectMapper.writeValueAsString(result);
        } catch (Exception e) {
            log.error("Error executing script tool", e);
            throw new RuntimeException("Failed to execute script tool", e);
        }
    }

    @Override
    public String getType() {
        return "script";
    }
}